<script setup>
import { ref } from 'vue';
import { onLoad, onReachBottom, onShareAppMessage } from '@dcloudio/uni-app'
import { uniFetch } from '../../api/uni-fetch';
import { useUserStore } from '/store/user.js'

const store = useUserStore()

// 数据定义
const groupBuyList = ref([])
const page = ref(1)
const total = ref(0)
const hasMore = ref(true)
const loading = ref(false)

onShareAppMessage(() => {
	const openid = uni.getStorageSync("userLoginCode").openid || uni.getStorageSync("userLoginCode").user.openid
	return {
		title: '华靓甄选-团购列表',
		path: '/subpkg/GroupBuyList/GroupBuyList?invite_token=' + openid
	}
})

// 页面加载时获取数据
onLoad(() => {
  loadGroupBuyData()
})

// 获取团购商品数据
async function loadGroupBuyData() {
  // 防止重复加载
  if (loading.value || !hasMore.value) {
    return
  }
  
  try {
    loading.value = true
    
    const { data } = await uniFetch.post('/shop-group-buying/list', {
      app_id: uni.appId,
      page: page.value,
      pageSize: 10
    })
    
    // 处理数据
    if (data?.list && data.list.length > 0) {
      // 为每个商品添加随机已售数量（模拟数据）
      data.list.forEach(item => {
        item.soldCount = Math.floor(Math.random() * 300) + 50
      })
      
      // 追加数据到列表
      groupBuyList.value.push(...data.list)
      total.value = data.total
      
      // 判断是否还有更多数据
      if (groupBuyList.value.length >= total.value) {
        hasMore.value = false
      }
      
      // 增加页码
      page.value++
    } else {
      // 没有更多数据
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取团购商品失败:', error)
    uni.showToast({
      title: '获取团购商品失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 触底加载更多
onReachBottom(() => {
  if (hasMore.value && !loading.value) {
    loadGroupBuyData()
  }
})

// 跳转商品详情
function toProductDetail(item) {
  uni.navigateTo({
		url: `/pages/ProductDetails/ProductDetails?goodsId=${item?.product_id}&groudId=${item?.id}&group_price=${item?.group_price}`
	})
}

// 购买商品
function buyProduct(item) {
  uni.navigateTo({
    url: `/subpkg/CreatOrder/CreatOrder?goodsId=${item.product_id}&num=1&groudId=${item.id}&group_price=${item.group_price}`
  })
}
</script>

<template>
  <view class="group-buy-list-page">
    
    <!-- 团购商品列表 -->
    <view class="group-buy-list">
      <view 
        v-for="item in groupBuyList" 
        :key="item.id" 
        class="group-buy-card"
        @click="toProductDetail(item)"
      >
        <!-- 商品图片 -->
        <view class="goods-image">
          <image :src="item.productPic" mode="aspectFill"></image>
          <!-- 团购标签 -->
          <view class="group-buy-tag">
            <text>团购</text>
          </view>
          <!-- 已售数量 -->
          <view class="sold-count">
            已售 {{ item.sold }}
          </view>
        </view>
        
        <!-- 商品信息 -->
        <view class="goods-info">
          <view class="goods-title">{{ item.title }}</view>
          
          <!-- 价格信息 -->
          <view class="price-container">
            <view class="price-wrapper">
              <text class="price-symbol">¥</text>
              <text class="group-price">
                {{ item.group_price }}
              </text>
            </view>
            
            <!-- 团购进度 -->
            <view class="group-progress">
              <view class="progress-bar">
                <view 
                  class="progress-fill" 
                  :style="{ width: `100%` }"
                ></view>
              </view>
              <text class="progress-text">
                {{ item.sold }}人已团
              </text>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="action-buttons">
            <button size="mini" class="buy-btn" @click.stop="buyProduct(item)">
              购买
            </button>
          </view>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="loading">
        <text>加载中...</text>
      </view>
      
      <!-- 没有更多数据提示 -->
      <view class="no-more" v-if="!hasMore && groupBuyList.length > 0">
        <text>没有更多团购商品了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="!hasMore && groupBuyList.length === 0">
        <image src="/static/images/empty.png" mode="aspectFit"></image>
        <text>暂无团购商品</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.group-buy-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 30rpx;
}

.group-buy-list {
  padding: 20rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.group-buy-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  width: 48.5%; /* 两列布局，留出间距 */
}

.goods-image {
  position: relative;
  width: 100%;
  height: 300rpx; /* 调整高度以适应两列布局 */
  overflow: hidden;
  
  image {
    width: 100%;
    height: 100%;
  }
  
  .group-buy-tag {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    background-color: #3bae43; /* 改为绿色 */
    color: #fff;
    padding: 8rpx 20rpx;
    border-radius: 100rpx;
    font-size: 24rpx;
  }
  
  .sold-count {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    padding: 8rpx 20rpx;
    border-radius: 100rpx;
    font-size: 24rpx;
  }
}

.goods-info {
  padding: 20rpx;
}

.goods-title {
  font-size: 28rpx; /* 调整字体大小以适应两列布局 */
  color: #333;
  margin-bottom: 16rpx;
  line-height: 42rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis; 
  overflow: hidden;
  height: 84rpx;
}

.price-wrapper {
  display: flex;
  align-items: baseline;
  margin-bottom: 12rpx;
  
  .price-symbol {
    font-size: 24rpx;
    color: #3bae43; /* 改为绿色 */
  }
  
  .group-price {
    font-size: 32rpx;
    font-weight: bold;
    color: #3bae43; /* 改为绿色 */
    margin-right: 10rpx;
  }
  
  .original-price {
    font-size: 20rpx;
    color: #999;
    text-decoration: line-through;
  }
}

.group-progress {
  
  .progress-bar {
    width: 100%;
    height: 6rpx;
    background-color: #f0f0f0;
    border-radius: 3rpx;
    overflow: hidden;
    margin-bottom: 6rpx;
    
    .progress-fill {
      height: 100%;
      background-color: #3bae43; /* 改为绿色 */
      border-radius: 3rpx;
    }
  }
  
  .progress-text {
    font-size: 20rpx;
    color: #666;
  }
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  
  button {
    flex: 0.4;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 30rpx;
    font-size: 22rpx;
    margin: 0 8rpx;
  }
  
  .buy-btn {
    background-color: #3bae43; /* 改为绿色 */
    color: #fff;
    border: none;
  }
}

.load-more,
.no-more,
.empty-state {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
  width: 100%; /* 确保提示信息占满整行 */
}

.empty-state {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
    opacity: 0.5;
  }
}
</style>
